package com.wave.wavesystem.common.util;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import wave.common.exception.WaveBusinessException;
import wave.common.pojo.entity.Query;

import java.lang.reflect.Field;

/**
 * @author 夕下风波
 * @date 2024-12-03 23:10
 * @description 构建实体查询条件
 */

public class Condition {

    /**
     * 根据实体构建对应的查询条件
     *
     * @param entity 查询实体 ，里面包含需要查询的字段
     */
    public static <T> QueryWrapper getQueryWrapper(T entity) {
        QueryChain<?> queryChain = QueryChain.of(entity.getClass());
        return getQueryWrapper(entity, queryChain);
    }

    public static <T> QueryWrapper getQueryWrapper(T entity, BaseMapper<?> baseMapper) {
        QueryChain<?> queryChain = QueryChain.of(baseMapper);
        return getQueryWrapper(entity, queryChain);
    }

    private static <T> QueryWrapper getQueryWrapper(T entity, QueryChain<?> queryChain) {
        Field[] searchFields = entity.getClass().getDeclaredFields();
        for (Field searchField : searchFields) {
            searchField.setAccessible(true);
            try {
                if (Func.isNotEmpty(searchField) && Func.isNotEmpty(searchField.get(entity))) {
                    String filedName = Func.camelToUnderline(searchField.getName());
                    queryChain.eq(filedName, searchField.get(entity));
                }
            } catch (IllegalAccessException e) {
                throw new WaveBusinessException();
            }
        }
        return queryChain;
    }

    /**
     * 获取分页
     *
     * @param query 分页参数
     */
    public static <T> Page<T> getPage(Query query) {
        return new Page<>(query.getPageNum(), query.getPageSize());
    }

}
